package com.spa.infrastructure.service.yunxin;

import com.spa.infrastructure.exception.SpaException;
import com.spa.infrastructure.util.RedisUtil;
import com.spa.infrastructure.util.StringUtils;
import com.winnerlook.model.PrivacyBindBodyAxb;
import com.winnerlook.model.VoiceNotifyBody;
import com.winnerlook.model.VoiceResponseResult;
import com.winnerlook.service.VoiceSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

/**
 * 虚拟电话
 */
@Service
@Slf4j
public class VoiceSenderService {

    @Value("${yunXin.accountId}")
    private String accountId;

    @Value("${yunXin.token}")
    private String token;

    @Value("${yunXin.accountId_SU}")
    private String accountId_SU;

    @Value("${yunXin.token_SU}")
    private String token_SU;

    private static final String VOICE_AXB = "VOICE_AXB:";

    @Value("${voice-bind-second:10}")
    private int second;

    @Autowired
    private RedisUtil redisUtil;

    public String bind(String bindNumberA, String bindNumberB) throws Exception {
        log.info("bindNumberA : {}, bindNumberB : {}", bindNumberA, bindNumberB);
        String key = VOICE_AXB + bindNumberA + ":" + bindNumberB;
        String middleNumber = redisUtil.get(key);
        if (StringUtils.isNotEmpty(middleNumber)) {
            return middleNumber;
        }
        PrivacyBindBodyAxb bindBodyAxb = new PrivacyBindBodyAxb();
        bindBodyAxb.setBindNumberA(bindNumberA);
        bindBodyAxb.setBindNumberB(bindNumberB);
        bindBodyAxb.setMaxBindingTime(second);
        VoiceResponseResult voiceResponseResult = VoiceSender.httpPrivacyBindAxb(bindBodyAxb, accountId, token);
        log.info("VoiceResponseResult : {}", voiceResponseResult);
        if (!"000000".equals(voiceResponseResult.getResult())) {
            throw new SpaException("您拨打的电话正在通话中，请稍后再拨！");
        }
        redisUtil.set(key, voiceResponseResult.getMiddleNumber(), second);
        return voiceResponseResult.getMiddleNumber();
    }

    /**
     * 语音短信
     * 测试templateId 402411
     * LinkedHashMap<String, String> templateArgs = new LinkedHashMap<>();
     * templateArgs.put("var1",orderCode);
     * @throws Exception
     */
    public void send(String phone, LinkedHashMap<String, String> templateArgs, String templateId) throws Exception {
        log.info("VoiceSenderService-send: {}, {}, {}", phone, templateArgs, templateId);
        VoiceNotifyBody voiceNotifyBody = new VoiceNotifyBody();
        voiceNotifyBody.setCalleeNumber(phone);
        voiceNotifyBody.setTemplateId(templateId);
        voiceNotifyBody.setTemplateArgs(templateArgs);
        VoiceResponseResult voiceResponseResult = VoiceSender.httpSendVoiceNotify(voiceNotifyBody, accountId_SU, token_SU);
        log.info("VoiceResponseResult : {}", voiceResponseResult);
    }

}
